#include "SortedSquares997.h"
#include <stdlib.h>

vector<int> SortedSquares997::sortedSquares(vector<int>& A)
{
	vector<int> outVec;

	int preValue = 0;
	int mimIndex = -1;
	for (vector<int>::size_type i = 0; i < A.size(); i++)
	{
		int item = abs(A[i]);

		if (i == 0)
		{
			if (A.size() == 1)
			{
				mimIndex = 0;
			}

			preValue = item;
			continue;
		}

		if (preValue < item)
		{
			mimIndex = i - 1;
			break;
		}
		else if (i >= A.size() - 1)
		{
			mimIndex = A.size() - 1;
		}

		preValue = item;
	}

	if (mimIndex >= 0)
	{
		outVec.push_back(abs(A[mimIndex]) * abs(A[mimIndex]));
	}

	int idxL = mimIndex - 1;
	int idxR = mimIndex + 1;

	while (idxL >= 0 || idxR < A.size())
	{
		if (idxL >= 0 && idxR < A.size())
		{
			int valueL = abs(A[idxL]);
			int valueR = abs(A[idxR]);

			if (valueL > valueR)
			{
				outVec.push_back(valueR * valueR);
				idxR++;
			}
			else if (valueL < valueR)
			{
				outVec.push_back(valueL * valueL);
				idxL--;
			}
			else
			{
				outVec.push_back(valueR * valueR);
				idxR++;
				outVec.push_back(valueL * valueL);
				idxL--;
			}
		}
		else if (idxL >= 0)
		{
			int valueL = abs(A[idxL]);
			outVec.push_back(valueL * valueL);
			idxL--;
		}
		else 
		{
			int valueR = abs(A[idxR]);
			outVec.push_back(valueR * valueR);
			idxR++;
		}
	}

	return outVec;
}



vector<int> SortedSquares997::sortedSquares_1(vector<int>& A)
{
	vector<int> outVec(A.size());

	for (int idxL = 0, idxR = A.size() - 1, idxOut = A.size() - 1; idxL <= idxR; )
	{
		if (-A[idxL] > A[idxR])
		{
			outVec[idxOut] = A[idxL] * A[idxL];
			idxL++;
		}
		else
		{
			outVec[idxOut] = A[idxR] * A[idxR];
			idxR--;
		}
		idxOut--;
	}

	return outVec;
}


void SortedSquares997::test()
{
	vector<int> in997 = { -2 };
	vector<int> out997 = this->sortedSquares_1(in997);

	vector<int> in997_1 = { -4, -3, -2, 1, 2, 3, 4, 5, 6, 7 };
	vector<int> out997_1 = this->sortedSquares_1(in997_1);

	vector<int> in997_2 = { -4, 0 };
	vector<int> out997_2 = this->sortedSquares_1(in997_2);

	vector<int> in997_3 = { -4, -3, -1 };
	vector<int> out997_3 = this->sortedSquares_1(in997_3);

	vector<int> in997_4 = { 4, 10, 20 };
	vector<int> out997_4 = this->sortedSquares_1(in997_4);
}